{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# AI for Good Workshop 2025\n",
    "\n",
    "[![image](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/opengeos/segment-geospatial/blob/main/docs/workshops/AIforGood_2025.ipynb)\n",
    "\n",
    "Join us for the AI for Good Workshop 2025, part of the UN's [AI for Good](https://aiforgood.itu.int) workshop series! This workshop will take place online on February 5, 2025, from 9:00 AM to 10:30 AM EST. It is free and open to the public. Please register using this link: [Mastering Remote Sensing Image Segmentation with AI: A Hands-On Workshop with the Segment Anything Model](https://aiforgood.itu.int/event/mastering-remote-sensing-image-segmentation-with-ai-a-hands-on-workshop-with-the-segment-anything-model/).\n",
    "\n",
    "## Overview\n",
    "\n",
    "Built upon Meta’s Segment Anything Model ([SAM](https://ai.meta.com/sam2)), the [SAMGeo](https://samgeo.gishub.org) Python package brings advanced segmentation capabilities to geospatial data. This hands-on workshop is tailored for geospatial enthusiasts, researchers, and professionals eager to unlock the potential of GeoAI in their projects.\n",
    "\n",
    "Participants will explore how to leverage SAMGeo for accurate and efficient image segmentation of satellite and aerial imagery. The workshop includes step-by-step demonstrations and practical exercises covering:\n",
    "\n",
    "-   **Introduction to SAM and SAMGeo:** Learn the architecture and functionality of SAM and its transformative applications in geospatial analysis.\n",
    "-   **Data Preparation:** Prepare geospatial datasets with multi-spectral channels for segmentation tasks.\n",
    "-   **Hands-On with SAMGeo:** Leverage SAMGeo to segment geospatial features (e.g., buildings, trees, water bodies) using prompts such as point coordinates, bounding boxes, and text.\n",
    "-   **Postprocessing Techniques:** Calculate geometric properties of segmented features, filter results, and extract meaningful insights.\n",
    "-   **Data Visualization:** Visualize object masks and segmented features in standard geospatial formats for analysis and reporting.\n",
    "\n",
    "By the end of the workshop, participants will gain practical experience applying SAMGeo to real-world geospatial challenges and leave equipped with new tools to elevate their geospatial data workflows.\n",
    "\n",
    "### Target audience\n",
    "\n",
    "This workshop is ideal for geospatial data scientists, remote sensing analysts, researchers, and anyone interested in applying AI to geospatial data.\n",
    "\n",
    "### Prerequisites\n",
    "\n",
    "-   A Google Colab account\n",
    "-   Basic understanding of Python programming and geospatial data concepts is recommended\n",
    "\n",
    "## Recording\n",
    "\n",
    "The recording of the workshop is available on YouTube: <https://www.youtube.com/watch?v=pTlIIr-ZS4s>\n",
    "\n",
    "## Introduction to SAM and SAMGeo\n",
    "\n",
    "The Segment Anything Model ([SAM](https://segment-anything.com)), introduced by Meta AI in April 2023, represents a significant advancement in computer vision, particularly in the field of image segmentation. Designed as a promptable segmentation model, SAM is capable of generating accurate segmentation masks based on various prompts, such as points, bounding boxes, or textual inputs. A notable feature of SAM is its zero-shot transfer ability, allowing it to adapt to new image distributions and tasks without additional training. This adaptability is largely attributed to its training on the extensive [SA-1B dataset](https://ai.meta.com/datasets/segment-anything/), which comprises over 1 billion segmentation masks across 11 million images.\n",
    "\n",
    "Building upon the foundation laid by SAM, Meta AI released Segment Anything Model 2 ([SAM 2](https://ai.meta.com/sam2/)) in August 2024. SAM 2 extends the capabilities of its predecessor by introducing real-time, promptable object segmentation in both images and videos. This unified model achieves state-of-the-art performance, enabling fast and precise selection of any object in any visual context. Key enhancements in SAM 2 include improved accuracy and processing speed, advanced prompting techniques, and the ability to handle video segmentation tasks seamlessly.\n",
    "\n",
    "Building on the success of SAM and SAM 2, the SAMGeo Python package extends these capabilities to geospatial data. SAMGeo empowers users to perform advanced image segmentation tasks on satellite and aerial imagery, enabling the extraction of valuable insights from geospatial datasets. By leveraging the power of SAMGeo, geospatial professionals can streamline their workflows, enhance data analysis, and unlock new possibilities in remote sensing applications.\n",
    "\n",
    "For more information on SAM and SAMGeo, please check out the slides from here: <https://bit.ly/aiforgood-samgeo>.\n",
    "\n",
    "## Environment setup\n",
    "\n",
    "### Install the required packages locally\n",
    "\n",
    "If you are running this notebook locally, you can install the required packages using the following commands:\n",
    "\n",
    "```bash\n",
    "conda create -n sam python=3.12\n",
    "conda activate sam\n",
    "conda install -c conda-forge mamba\n",
    "mamba install -c conda-forge segment-geospatial groundingdino-py gdal\n",
    "```\n",
    "\n",
    "### Use Google Colab\n",
    "\n",
    "If you are using Google Colab, make sure you use GPU runtime for this notebook. Go to `Runtime` -> `Change runtime type` and select `GPU` as the hardware accelerator. Then you can run the following cell to install the required packages."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install segment-geospatial groundingdino-py"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Image segmentation with point prompts\n",
    "\n",
    "In this section, we will demonstrate how to segment objects from remote sensing imagery using point prompts with the Segment Anything Model 2 (SAM 2).\n",
    "\n",
    "### Import libraries\n",
    "\n",
    "Import the required libraries, including [leafmap](https://leafmap.org) and [samgeo](https://samgeo.gishub.org)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap\n",
    "from samgeo import SamGeo2, regularize"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create an interactive map\n",
    "\n",
    "Create an interactive map using leafmap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map(center=[47.653287, -117.588070], zoom=16, height=\"800px\")\n",
    "m.add_basemap(\"Satellite\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download a sample image\n",
    "\n",
    "Pan and zoom the map to select the area of interest. Use the draw tools to draw a polygon or rectangle on the map. If no geometry is drawn, the default bounding box will be used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if m.user_roi is not None:\n",
    "    bbox = m.user_roi_bounds()\n",
    "else:\n",
    "    bbox = [-117.6029, 47.65, -117.5936, 47.6563]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download the image within the selected region using `map_tiles_to_geotiff()` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = \"satellite.tif\"\n",
    "leafmap.map_tiles_to_geotiff(\n",
    "    output=image, bbox=bbox, zoom=18, source=\"Satellite\", overwrite=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Important note:** The code is provided for educational purposes only. By using the information and code provided, users acknowledge that they are using the APIs and models at their own risk and agree to comply with any applicable laws and regulations. Users who intend to download a large number of image tiles from any basemap are advised to contact the basemap provider to obtain permission before doing so. Unauthorized use of the basemap or any of its components may be a violation of copyright laws or other applicable laws and regulations.\n",
    "\n",
    "Alternatively, you can also use your own image. Uncomment and run the following cell to use your own image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# image = '/path/to/your/own/image.tif'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the downloaded image on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.layers[-1].visible = False\n",
    "m.add_raster(image, layer_name=\"Image\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize SAM class\n",
    "\n",
    "Set `automatic=False` to enable the `SAM2ImagePredictor`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam = SamGeo2(\n",
    "    model_id=\"sam2-hiera-large\",\n",
    "    automatic=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Specify the image to segment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.set_image(image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segment the image\n",
    "\n",
    "Use the `predict_by_points()` method to segment the image with specified point coordinates. You can use the draw tools to add place markers on the map. If no point is added, the default sample points will be used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if m.user_rois is not None:\n",
    "    point_coords_batch = m.user_rois\n",
    "else:\n",
    "    point_coords_batch = [\n",
    "        [-117.599896, 47.655345],\n",
    "        [-117.59992, 47.655167],\n",
    "        [-117.599928, 47.654974],\n",
    "        [-117.599518, 47.655337],\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Segment the objects using the point prompts and save the output masks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.predict_by_points(\n",
    "    point_coords_batch=point_coords_batch,\n",
    "    point_crs=\"EPSG:4326\",\n",
    "    output=\"mask.tif\",\n",
    "    dtype=\"uint8\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Display the result\n",
    "\n",
    "Add the segmented image to the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_raster(\"mask.tif\", cmap=\"viridis\", nodata=0, opacity=0.7, layer_name=\"Mask\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/49e413b9-e159-4d72-bf23-a0318bc82d44)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Use an existing vector dataset as point prompts\n",
    "\n",
    "Alternatively, you can specify a file path or HTTP URL to a vector dataset containing point geometries."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "geojson = \"https://github.com/opengeos/datasets/releases/download/places/wa_building_centroids.geojson\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the vector dataawr on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map()\n",
    "m.add_raster(image, layer_name=\"Image\")\n",
    "m.add_circle_markers_from_xy(\n",
    "    geojson, radius=3, color=\"red\", fill_color=\"yellow\", fill_opacity=0.8\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/f0d3ff1e-15fa-4bd3-ac15-637e8d63527d)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segment image with a vector dataset\n",
    "\n",
    "Segment the image using the specified file path to the vector dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_masks = \"building_masks.tif\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.predict_by_points(\n",
    "    point_coords_batch=geojson,\n",
    "    point_crs=\"EPSG:4326\",\n",
    "    output=output_masks,\n",
    "    dtype=\"uint8\",\n",
    "    multimask_output=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the segmented masks on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_raster(\n",
    "    output_masks, cmap=\"jet\", nodata=0, opacity=0.7, layer_name=\"Building masks\"\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/262e1a31-1648-47d2-9e71-c85ab15b1a5c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Clean up the result\n",
    "\n",
    "Remove small objects from the segmented masks, fill holes, and compute geometric properties."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "out_vector = \"building_vector.geojson\"\n",
    "out_image = \"buildings.tif\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "array, gdf = sam.region_groups(\n",
    "    output_masks, min_size=200, out_vector=out_vector, out_image=out_image\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gdf.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/af9ffa11-8ebe-4b42-8cba-3f5bcc4912f4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Regularize building footprints\n",
    "\n",
    "Regularize the building footprints using the `regularize()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_regularized = \"building_regularized.geojson\"\n",
    "regularize(out_vector, output_regularized)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the regularized building footprints on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map()\n",
    "m.add_raster(image, layer_name=\"Image\")\n",
    "style = {\n",
    "    \"color\": \"#ffff00\",\n",
    "    \"weight\": 2,\n",
    "    \"fillColor\": \"#7c4185\",\n",
    "    \"fillOpacity\": 0,\n",
    "}\n",
    "m.add_raster(out_image, cmap=\"tab20\", opacity=0.7, nodata=0, layer_name=\"Buildings\")\n",
    "m.add_vector(\n",
    "    output_regularized, style=style, layer_name=\"Building regularized\", info_mode=None\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/b39ee029-2089-45b8-8ac0-ba0d750cec22)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Interactive segmentation\n",
    "\n",
    "Place markers on the map to segment the objects interactively."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.show_map()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://github.com/user-attachments/assets/4f487505-6e89-4892-9a70-95ab0aa69cb6)\n",
    "\n",
    "## Image segmentation with box prompts\n",
    "\n",
    "In this section, we will demonstrate how to segment objects from remote sensing imagery using box prompts with the Segment Anything Model 2 (SAM 2).\n",
    "\n",
    "### Import libraries\n",
    "\n",
    "Import the required libraries, including [leafmap](https://leafmap.org) and [samgeo](https://samgeo.gishub.org)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap\n",
    "from samgeo import SamGeo2, raster_to_vector, regularize"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create an interactive map\n",
    "\n",
    "Create an interactive map using leafmap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map(center=[47.653287, -117.588070], zoom=16, height=\"800px\")\n",
    "m.add_basemap(\"Satellite\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download a sample image\n",
    "\n",
    "Pan and zoom the map to select the area of interest. Use the draw tools to draw a polygon or rectangle on the map. If no geometry is drawn, the default bounding box will be used."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if m.user_roi is not None:\n",
    "    bbox = m.user_roi_bounds()\n",
    "else:\n",
    "    bbox = [-117.6029, 47.65, -117.5936, 47.6563]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download the image within the selected region using `map_tiles_to_geotiff()` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = \"satellite.tif\"\n",
    "leafmap.map_tiles_to_geotiff(\n",
    "    output=image, bbox=bbox, zoom=18, source=\"Satellite\", overwrite=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also use your own image. Uncomment and run the following cell to use your own image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# image = '/path/to/your/own/image.tif'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the downloaded image on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.layers[-1].visible = False\n",
    "m.add_raster(image, layer_name=\"Image\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize SAM class\n",
    "\n",
    "Set `automatic=False` to enable the `SAM2ImagePredictor`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam = SamGeo2(\n",
    "    model_id=\"sam2-hiera-large\",\n",
    "    automatic=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Specify the image to segment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.set_image(image)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the map. Use the drawing tools to draw some rectangles around the features you want to extract, such as trees, buildings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create bounding boxes\n",
    "\n",
    "If no rectangles are drawn, the default bounding boxes will be used as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if m.user_rois is not None:\n",
    "    boxes = m.user_rois\n",
    "else:\n",
    "    boxes = [\n",
    "        [-117.5995, 47.6518, -117.5988, 47.652],\n",
    "        [-117.5987, 47.6518, -117.5979, 47.652],\n",
    "    ]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segment the image\n",
    "\n",
    "Use the `predict()` method to segment the image with specified bounding boxes. The `boxes` parameter accepts a list of bounding box coordinates in the format of [[left, bottom, right, top], [left, bottom, right, top], ...], a GeoJSON dictionary, or a file path to a GeoJSON file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.predict(boxes=boxes, point_crs=\"EPSG:4326\", output=\"mask.tif\", dtype=\"uint8\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Display the result\n",
    "\n",
    "Add the segmented image to the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_raster(\"mask.tif\", cmap=\"viridis\", nodata=0, layer_name=\"Mask\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Use an existing vector dataset as box prompts\n",
    "\n",
    "Alternatively, you can specify a file path to a vector dataset. Let's download a sample vector dataset from GitHub."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://github.com/opengeos/datasets/releases/download/samgeo/building_bboxes.geojson\"\n",
    "geojson = \"building_bboxes.geojson\"\n",
    "leafmap.download_file(url, geojson)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the vector dataset on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map()\n",
    "m.add_raster(image, layer_name=\"Image\")\n",
    "style = {\n",
    "    \"color\": \"#ffff00\",\n",
    "    \"weight\": 2,\n",
    "    \"fillColor\": \"#7c4185\",\n",
    "    \"fillOpacity\": 0,\n",
    "}\n",
    "m.add_vector(geojson, style=style, zoom_to_layer=True, layer_name=\"Bboxes\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/95e8d2a5-9354-4694-b928-195a85bbb2e6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segment image with box prompts\n",
    "\n",
    "Segment the image using the specified file path to the vector mask."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_masks = \"building_masks.tif\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.predict(\n",
    "    boxes=geojson,\n",
    "    point_crs=\"EPSG:4326\",\n",
    "    output=output_masks,\n",
    "    dtype=\"uint8\",\n",
    "    multimask_output=False,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the segmented masks on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_raster(\n",
    "    output_masks, cmap=\"jet\", nodata=0, opacity=0.5, layer_name=\"Building masks\"\n",
    ")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/6f2d4f1f-dfc1-4dfa-8acb-642e1afb9c4a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Convert raster to vector\n",
    "\n",
    "Convert the segmented masks to a vector format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_vector = \"building_vector.geojson\"\n",
    "raster_to_vector(output_masks, output_vector)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Regularize building footprints\n",
    "\n",
    "Regularize the building footprints using the `regularize()` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_regularized = \"building_regularized.geojson\"\n",
    "regularize(output_vector, output_regularized)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the regularized building footprints on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_vector(\n",
    "    output_regularized, style=style, layer_name=\"Building regularized\", info_mode=None\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/c4b77056-9fd1-4ce8-9740-1b9d4f993040)\n",
    "\n",
    "## Image segmentation with text prompts\n",
    "\n",
    "In this section, we will demonstrate how to segment objects from remote sensing imagery using text prompts with the Segment Anything Model 2 (SAM 2).\n",
    "\n",
    "### Import libraries\n",
    "\n",
    "Import the required libraries, including [leafmap](https://leafmap.org) and [samgeo](https://samgeo.gishub.org)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap\n",
    "from samgeo.text_sam import LangSAM"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create an interactive map\n",
    "\n",
    "Create an interactive map using leafmap."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = leafmap.Map(center=[-22.17615, -51.253043], zoom=18, height=\"800px\")\n",
    "m.add_basemap(\"SATELLITE\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download a sample image\n",
    "\n",
    "Pan and zoom the map to select the area of interest. Use the draw tools to draw a polygon or rectangle on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "bbox = m.user_roi_bounds()\n",
    "if bbox is None:\n",
    "    bbox = [-51.2565, -22.1777, -51.2512, -22.175]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Download the image within the selected region using `map_tiles_to_geotiff()` function."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "image = \"Image.tif\"\n",
    "leafmap.map_tiles_to_geotiff(\n",
    "    output=image, bbox=bbox, zoom=19, source=\"Satellite\", overwrite=True\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can also use your own image. Uncomment and run the following cell to use your own image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# image = '/path/to/your/own/image.tif'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Display the downloaded image on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.layers[-1].visible = False\n",
    "m.add_raster(image, layer_name=\"Image\")\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize LangSAM class\n",
    "\n",
    "The initialization of the LangSAM class might take a few minutes. The initialization downloads the model weights and sets up the model for inference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam = LangSAM(model_type=\"sam2-hiera-large\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Specify text prompts\n",
    "\n",
    "Specify the text prompt to segment the objects in the image. The text prompt can be a single word or a phrase that describes the object you want to segment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "text_prompt = \"tree\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segment the image\n",
    "\n",
    "Part of the model prediction includes setting appropriate thresholds for object detection and text association with the detected objects. These threshold values range from 0 to 1 and are set while calling the predict method of the LangSAM class.\n",
    "\n",
    "`box_threshold`: This value is used for object detection in the image. A higher value makes the model more selective, identifying only the most confident object instances, leading to fewer overall detections. A lower value, conversely, makes the model more tolerant, leading to increased detections, including potentially less confident ones.\n",
    "\n",
    "`text_threshold`: This value is used to associate the detected objects with the provided text prompt. A higher value requires a stronger association between the object and the text prompt, leading to more precise but potentially fewer associations. A lower value allows for looser associations, which could increase the number of associations but also introduce less precise matches.\n",
    "\n",
    "Remember to test different threshold values on your specific data. The optimal threshold can vary depending on the quality and nature of your images, as well as the specificity of your text prompts. Make sure to choose a balance that suits your requirements, whether that's precision or recall."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.predict(image, text_prompt, box_threshold=0.24, text_threshold=0.24)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Visualize the results\n",
    "\n",
    "Show the result with bounding boxes on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.show_anns(\n",
    "    cmap=\"Greens\",\n",
    "    box_color=\"red\",\n",
    "    title=\"Automatic Segmentation of Trees\",\n",
    "    blend=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/fd1a6a46-7fc6-45f5-8408-d648f2b5bbfe)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Show the result without bounding boxes on the map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.show_anns(\n",
    "    cmap=\"Greens\",\n",
    "    add_boxes=False,\n",
    "    alpha=0.5,\n",
    "    title=\"Automatic Segmentation of Trees\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/11843d0f-9caa-4e71-905f-17d363640cef)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Show the result as a grayscale image."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.show_anns(\n",
    "    cmap=\"Greys_r\",\n",
    "    add_boxes=False,\n",
    "    alpha=1,\n",
    "    title=\"Automatic Segmentation of Trees\",\n",
    "    blend=False,\n",
    "    output=\"trees.tif\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/2fb80bbf-4d07-401e-8a57-ccde74ae3115)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Convert the result to a vector format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "da, gdf = sam.region_groups(\n",
    "    image=\"trees.tif\",\n",
    "    min_size=100,\n",
    "    out_csv=\"objects.csv\",\n",
    "    out_image=\"objects.tif\",\n",
    "    out_vector=\"objects.gpkg\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Show the results on the interactive map."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "m.add_raster(\"objects.tif\", layer_name=\"Trees\", palette=\"Greens\", opacity=0.5, nodata=0)\n",
    "style = {\n",
    "    \"color\": \"#3388ff\",\n",
    "    \"weight\": 2,\n",
    "    \"fillColor\": \"#7c4185\",\n",
    "    \"fillOpacity\": 0.5,\n",
    "}\n",
    "m.add_vector(\"objects.gpkg\", layer_name=\"Vector\", style=style)\n",
    "m"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Interactive segmentation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sam.show_map()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![](https://i.imgur.com/wydt5Xt.gif)\n",
    "\n",
    "## Timeseries images segmentation\n",
    "\n",
    "### Import libraries\n",
    "\n",
    "Import the required libraries, including [leafmap](https://leafmap.org) and [samgeo](https://samgeo.gishub.org)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap\n",
    "from samgeo import SamGeo2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download sample data\n",
    "\n",
    "For now, SamGeo2 supports remote sensing data in the form of RGB images, 8-bit integer. Make sure all images are in the same width and height. Let's download a sample timeseries dataset from GitHub."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://github.com/opengeos/datasets/releases/download/raster/landsat_ts.zip\"\n",
    "leafmap.download_file(url)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize the model\n",
    "\n",
    "Initialize the SamGeo2 class with the model ID and set the `video` parameter to `True`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor = SamGeo2(\n",
    "    model_id=\"sam2-hiera-large\",\n",
    "    video=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Specify the input data\n",
    "\n",
    "Point to the directory containing the images or the video file."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "video_path = \"landsat_ts\"\n",
    "predictor.set_video(video_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Specify the input prompts\n",
    "\n",
    "The prompts can be points and boxes. The points are represented as a list of tuples, where each tuple contains the x and y coordinates of the point. The boxes are represented as a list of tuples, where each tuple contains the x, y, width, and height of the box."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.show_images()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompts = {\n",
    "    1: {\n",
    "        \"points\": [[1582, 933], [1287, 905], [1473, 998]],\n",
    "        \"labels\": [1, 1, 1],\n",
    "        \"frame_idx\": 0,\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.show_prompts(prompts, frame_idx=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/2290c685-5d08-4605-8859-ecc3d9986e8f)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Althernatively, prompts can be provided in lon/lat coordinates. The model will automatically convert the lon/lat coordinates to pixel coordinates when the `point_crs` parameter is set to the coordinate reference system of the lon/lat coordinates."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompts = {\n",
    "    1: {\n",
    "        \"points\": [[-74.3713, -8.5218], [-74.2973, -8.5306], [-74.3230, -8.5495]],\n",
    "        \"labels\": [1, 1, 1],\n",
    "        \"frame_idx\": 0,\n",
    "    },\n",
    "}\n",
    "predictor.show_prompts(prompts, frame_idx=0, point_crs=\"EPSG:4326\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Segment objects\n",
    "\n",
    "Segment the objects from the video or timeseries images."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.predict_video()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save results\n",
    "\n",
    "To save the results as gray-scale GeoTIFFs with the same georeference as the input images:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.save_video_segments(\"segments\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To save the results as blended images and MP4 video:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.save_video_segments_blended(\n",
    "    \"blended\", fps=5, output_video=\"segments_blended.mp4\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/111cada6-ada1-4785-8d37-385872bd7a4f)\n",
    "\n",
    "Preview the video."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import Video\n",
    "\n",
    "Video(\"segments_blended.mp4\", embed=True, width=600, height=400)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Video segmentation\n",
    "\n",
    "In this section, we will demonstrate how to segment objects from a video using the Segment Anything Model 2 (SAM 2).\n",
    "\n",
    "### Import libraries\n",
    "\n",
    "Import the required libraries, including [leafmap](https://leafmap.org) and [samgeo](https://samgeo.gishub.org)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import leafmap\n",
    "from samgeo import SamGeo2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize the model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor = SamGeo2(\n",
    "    model_id=\"sam2-hiera-large\",\n",
    "    video=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Specify the input data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "url = \"https://github.com/opengeos/datasets/releases/download/videos/cars.mp4\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "video_path = url\n",
    "predictor.set_video(video_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Specify the input prompts"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.show_images()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "prompts = {\n",
    "    1: {\n",
    "        \"points\": [[335, 203]],\n",
    "        \"labels\": [1],\n",
    "        \"frame_idx\": 0,\n",
    "    },\n",
    "    2: {\n",
    "        \"points\": [[420, 201]],\n",
    "        \"labels\": [1],\n",
    "        \"frame_idx\": 0,\n",
    "    },\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.show_prompts(prompts, frame_idx=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/5f55c814-2a86-45a0-b75c-84e2757b88d5)\n",
    "\n",
    "### Segment objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.predict_video(prompts)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Save results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "predictor.save_video_segments_blended(\"cars\", output_video=\"cars_blended.mp4\", fps=25)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "![image](https://github.com/user-attachments/assets/ef5a0310-26d1-4d64-a880-73b1e5de42c9)\n",
    "\n",
    "Preview the video."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from IPython.display import Video\n",
    "\n",
    "Video(\"cars_blended.mp4\", embed=True, width=600, height=400)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
